package com.qf.controller;

import com.alibaba.fastjson.JSONObject;
import com.qf.captcha.CaptchaCodeManager;
import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.ResponseUtil;
import com.qf.util.VerifyCodeUtils;
import com.qf.util.Base64;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * @author 金园
 * @create 2022/5/16
 * @Description
 * @className login
 * @packageName com.qf.controller
 */
@RestController
@RequestMapping("/admin/auth")
public class DtsAdminAuthController {
    @Autowired
    DtsRoleService roleService;
    @Autowired
    DtsPermissionService permissionService; 






    private static final Logger logger = LoggerFactory.getLogger(DtsAdminAuthController.class);
    @RequestMapping("/login")
    public Object login(@RequestBody Map<String,String> map, HttpSession session){
        //获取前端数据
        String code = map.get("code");
        String username = map.get("username");
        String password = map.get("password");
        String uuid = map.get("uuid");
        //从服务器获取生成的验证码
        String cachedCaptcha = CaptchaCodeManager.getCachedCaptcha(uuid);
        //验证
        if (code == null || !code.equalsIgnoreCase(cachedCaptcha)){
           return ResponseUtil.fail(-1,"验证码已失效或验证码错误");
        }
        //（shiro）登录操作
        Subject subject = SecurityUtils.getSubject();
        //获取token
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            //在控制台打印错误的堆栈信息,方便解决问题的
            e.printStackTrace();
            return ResponseUtil.fail(-1, "未知的账户");
        } catch (LockedAccountException e){
            e.printStackTrace();
            return ResponseUtil.fail(-1, "账户已锁定");
        } catch (CredentialsException e){
            e.printStackTrace();
            return ResponseUtil.fail(-1, "密码错误");
        }
        System.out.println(subject.hasRole("超级管理员"));
        System.out.println(subject.isPermitted("admin:category:read"));
        return ResponseUtil.ok(session.getId());
    }
    
    @RequestMapping("/captchaImage")
    public Object captchaImage() throws IOException {
        //1.生成验证码
        //指定位数验证码
        String code = VerifyCodeUtils.generateVerifyCode(1);
        //创建输出流对象
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //生成验证码图片
        VerifyCodeUtils.outputImage(110,35,outputStream,code);
        //UUID唯一标识
        String uuid = UUID.randomUUID().toString();
        //把验证码存入缓存中
        CaptchaCodeManager.addToCache(uuid,code,1);
        //讲uuid和code装入map中传回前端
        Map<String,Object> data = new HashMap<>();
                        //把输出流的内容转换为字节数组，要对验证码图片数组进行加密
        data.put("uuid",uuid);
        data.put("img", Base64.encode(outputStream.toByteArray()));
        //返回前端需要的数据类型
        return ResponseUtil.ok(data);
    }

    @RequiresAuthentication
    @RequestMapping("/logout")
    public Object login() {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();

        logger.info("【请求结束】系统管理->用户注销,响应结果:{}", JSONObject.toJSONString(currentUser.getSession().getId()));
        return ResponseUtil.ok();
    }
    //登录首页  获取当前登录的用户，角色， 权限等信息
    @RequestMapping("/info")
    public Object info(){
        Subject subject = SecurityUtils.getSubject();
        DtsAdmin admin = (DtsAdmin) subject.getPrincipal();
        Map<String,Object> data = new HashMap<>();
        
        Set<String> role = roleService.findRoleById(admin.getRoleIds());
        Set<String> perm = permissionService.findPermById(admin.getRoleIds());
        //需要查询角色
        data.put("roles",role);
        //用户名
        data.put("name",admin.getUsername());
        //需要查询权限
        data.put("perms",perm);
        //头像
        data.put("avatar",admin.getAvatar());


        return  ResponseUtil.ok(data);
    }

}
